/**
 * 投资圈界面
 */
 'use strict';
 import React, {Component} from 'react';
 import {
     View,
     ListView,
     Image,
     Text,
     TouchableOpacity,
     TouchableHighlight,
     StyleSheet,
     Alert,
     ScrollView,
     Dimensions,
     InteractionManager,
     AppRegistry
} from 'react-native';
import ImageButton from '../../component/ImageButton'
import ViewPager from 'react-native-viewpager';
import PullRefreshScrollView from 'react-native-pullrefresh-scrollview';
import WebImage from 'react-native-web-image'
import { HttpClient } from '../../../utils/HttpRequest';

var { height,width } =  Dimensions.get('window');

var IMGS = [
  'https://images.unsplash.com/photo-1441742917377-57f78ee0e582?h=1024',
  'https://images.unsplash.com/photo-1441716844725-09cedc13a4e7?h=1024',
  'https://images.unsplash.com/photo-1441448770220-76743f9e6af6?h=1024',
  'https://images.unsplash.com/photo-1441260038675-7329ab4cc264?h=1024',
  'https://images.unsplash.com/photo-1441126270775-739547c8680c?h=1024',
  'https://images.unsplash.com/photo-1440964829947-ca3277bd37f8?h=1024',
  'https://images.unsplash.com/photo-1440847899694-90043f91c7f9?h=1024'
];

const STORE_DATA={
    "api":"GetStoreList",
    "v":"1.0",
    "code":"0",
    "msg":"success",
    "data":[{
        "id":1,
        "title":"Pokemon go的版权在哪个公司？",
        "author":"aiko",
        "time":"07月15日",
        "fav":45,
        "tag":"推荐",
        "tagColor":"1",
        "image":"https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=3916074273,4067386700&fm=23&gp=0.jpg"
    },{
      "id":2,
      "title":"最强大脑爆最强黑幕，听音盲拧？",
      "author":"aiko",
      "time":"07月15日",
      "fav":45,
      "tag":"新动态",
      "tagColor":"2",
      "image":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488452434823&di=2a42a486b0223e39239b9449eb49fdcd&imgtype=0&src=http%3A%2F%2Fp2.ifengimg.com%2Fa%2F2016_40%2F401cb3bc2f5b71a_size36_w519_h425.jpg"
    },{
      "id":3,
      "title":"VR创业？想赚快钱的都散了吧",
      "author":"aiko",
      "time":"07月15日",
      "fav":45,
      "tag":"投资",
      "tagColor":"3",
      "image":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488452434823&di=6223e2c1d8d8e1049b375905d370a799&imgtype=0&src=http%3A%2F%2Fpic2.pedaily.cn%2F201603%2F20160328090538103810.png"
    },{
      "id":4,
      "title":"在中国有房有车，才是财富的象征？",
      "author":"aiko",
      "time":"07月15日",
      "fav":45,
      "tag":"创业",
      "tagColor":"4",
      "image":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488452485666&di=81bd97c2600caa895c2f9ebcc115e8f1&imgtype=0&src=http%3A%2F%2Fimage92.360doc.com%2FDownloadImg%2F2015%2F12%2F2309%2F63399184_1.png"
    },{
      "id":5,
      "title":"人工智能领域，下一个热门投资风口？",
      "author":"aiko",
      "time":"07月15日",
      "fav":45,
      "tag":"热门",
      "tagColor":"5",
      "image":"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1488452522747&di=a664d1159492e95b3e0df589e9644172&imgtype=0&src=http%3A%2F%2Fphotocdn.sohu.com%2F20151117%2FImg426770395.jpg"
    }
    ]
};

class FortuneGroup extends Component {

  /**
    * 加载耗时操作
    */
   componentDidMount() {
     this._getDataFromFetch();
   }

   constructor(props) {
      super(props);
      this.renderItem = this.renderItem.bind(this);
      this.state = {
          viewPagerDataSource: new ViewPager.DataSource({
              pageHasChanged: (p1, p2) => p1 !== p2,
            }).cloneWithPages(IMGS),
          listViewDataSource: new ListView.DataSource({
              rowHasChanged: (r1, r2) => r1 !== r2
            }).cloneWithRows(STORE_DATA.data === undefined ? [] : STORE_DATA.data),
      }
  }

  _getDataFromFetch() {
    var url = 'http://172.16.101.202/play/circle/getPostList4C';
    var fetchOptions = {
          method: 'POST',
          headers: {
            'Accept': 'application/json',
            //json形式
            'Content-Type': 'application/json'
          },
          body: 'boardId=1&pageNumber=1'
          //JSON.stringify(data)
        };

      fetch(url, fetchOptions)
        .then((response) => {
          alert(response.json());
          // return response.json();
        })
        // .then((responseJson) => {
        //   console.warn(responseJson);
        //     alert(responseJson);
        //   // alert(responseJson.postListPerPage.postList.length);
        // })
        .done();
  }

  renderPage (data) {
    return (
      <Image
        source={{uri: data}}
        style={styles.viewpager} />
    );
  }

  onRefresh(PullRefresh) {
      console.log('refresh');
      setTimeout(function(){
          PullRefresh.onRefreshEnd();
      },2000);
  }

  onLoadMore(PullRefresh) {
    var self = this;
    setTimeout(function(){
          // self.data = self.data.concat(['有种你滑我啊(新)']);
          // self.setState({
          //   dataSource: self.state.listViewDataSource.cloneWithRows(self.data)
          // });
          // PullRefresh.onLoadMoreEnd(); uncomment to end loadmore
      },2000);
    console.log('onLoadMore');
  }

  /**
    * Render a separator between rows
    */
  renderSeparator(sectionID: number, rowID: number, adjacentRowHighlighted: bool) {
      return (
        <View key={`${sectionID}-${rowID}`} style={styles.separator} />
      );
    }

  renderItem(data) {
      return (
        <View key={data.id} style={{marginLeft:15, marginTop:10, marginRight:15}}>
        <Image source={{uri:data.image}}  style={{width:(width-15*2), height:160, marginBottom:10}}/>
        <ImageButton icon={require('../../../resources/images/fortunegroup/img_1.png')} title={data.tag}/>
        <Text style={{fontSize:15, color:'#5A5A5A', marginTop:10}}>{data.title}</Text>
        <View style={{height:20, flexDirection:'row', marginTop:10, marginBottom:10, alignItems:'center'}}>
          <Image source={require('../../../resources/images/mine/icon_header.png')} style={{width:20, height:20, justifyContent:'center'}}/>
          <Text style={{width:35, fontSize:13, color:'#C7C7C7', marginLeft:5}}>{data.author}</Text>
          <Text style={{width:80, fontSize:13, color:'#C7C7C7', marginLeft:5}}>{data.time}</Text>
          <View style={{flex:1}}/>
          <Image source={require('../../../resources/images/fortunegroup/icon_like.png')} style={{width:13, height:10, justifyContent:'center'}}/>
          <Text style={{width:20, fontSize:11, color:'#C7C7C7', marginLeft:5}}>{data.fav}</Text>
        </View>
        </View>
      );
    }

  //进行渲染数据
  renderContent(dataSource) {
      return (
        <ListView
          initialListSize={1}
          renderScrollComponent={
            (props) => <PullRefreshScrollView
              onRefresh={(PullRefresh)=>this.onRefresh(PullRefresh)}
              onLoadMore={(PullRefresh)=>this.onLoadMore(PullRefresh)}
              useLoadMore={1}{...props} />
            }
          dataSource={this.state.listViewDataSource}
          renderRow={this.renderItem}
          style={{backgroundColor:'white',flex:1}}
          onEndReachedThreshold={10}
          enableEmptySections={true}
          renderSeparator={this.renderSeparator}
        />
      );
     }

render() {
    return (
      <View style = {styles.container}>
          {/* 导航 */}
          <View style={{height:49,backgroundColor:'#FEEF35',flexDirection:'row'}}>
                <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
                     <Text style={{color:'#222222'}}>投资圈</Text>
                </View>
          </View>
          <ViewPager
            style={styles.viewpager}
            dataSource={this.state.viewPagerDataSource}
            renderPage={this.renderPage}
            isLoop={true}
            autoPlay={true}/>
          <View style={{flex:2, backgroundColor:'#FFFFFF'}}>{this.renderContent(this.state.listViewDataSource)}</View>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:'#f0eff4'
  },
  header:{
      height:49,
      backgroundColor: '#293447',
  },
  viewpager: {
    flex: 1,
    width: width
  },
  rowItem:{
      flex:1,
      height:50,
      alignItems:'center',
      justifyContent:'center'
  },
  separator: {
      height: 1,
      backgroundColor: '#CCCCCC',
    },
    wrap_style: {
        height: 46,
        backgroundColor: 'white',
    },
    item_view: {
        height: 46,
        justifyContent: 'center',
    },
    item_img: {
        width: 23,
        height: 23,
        marginLeft: 17,
    },
    item_arrow_view: {
        height: 46,
        justifyContent: 'center',
        flex: 1,
        alignItems: 'flex-end',
        marginRight: 17
    }
});

export default FortuneGroup;
